<template>
  <div class="qa-chat-container">
    <!-- 左侧边栏 -->
    <aside class="sidebar">
      <!-- 历史会话列表 - 已屏蔽 -->
      <div v-if="false" class="history-section">
        <h3 class="section-title">历史会话列表</h3>
        <el-button type="primary" class="new-session-btn" @click="newSession">
          <el-icon><Plus /></el-icon> 新建会话
        </el-button>

        <el-collapse v-model="activeKey" class="session-collapse">
          <el-collapse-item name="today" title="今天">
            <div
              v-for="session in todaySessions"
              :key="session.id"
              class="session-item"
              :class="{ active: session.id === currentSessionId }"
              @click="loadSession(session)"
            >
              <span class="session-title">{{ session.title }}</span>
              <span class="session-time">{{
                formatTime(session.timestamp)
              }}</span>
            </div>
          </el-collapse-item>

          <el-collapse-item name="yesterday" title="昨天">
            <div
              v-for="session in yesterdaySessions"
              :key="session.id"
              class="session-item"
              :class="{ active: session.id === currentSessionId }"
              @click="loadSession(session)"
            >
              <span class="session-title">{{ session.title }}</span>
              <span class="session-time">{{
                formatTime(session.timestamp)
              }}</span>
            </div>
          </el-collapse-item>

          <el-collapse-item name="thisWeek" title="本周">
            <div
              v-for="session in thisWeekSessions"
              :key="session.id"
              class="session-item"
              :class="{ active: session.id === currentSessionId }"
              @click="loadSession(session)"
            >
              <span class="session-title">{{ session.title }}</span>
              <span class="session-time">{{
                formatTime(session.timestamp)
              }}</span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 快速问题推荐 -->
      <div class="quick-questions">
        <h3 class="section-title">快速问题推荐</h3>
        <el-space direction="vertical" class="quick-question-list" :size="8">
          <el-button
            v-for="q in quickQuestions"
            :key="q.id"
            type="default"
            class="quick-question-btn"
            @click="askQuickQuestion(q.text)"
          >
            <el-icon><Check /></el-icon> {{ q.text }}
          </el-button>
        </el-space>
      </div>
    </aside>

    <!-- 主内容区 -->
    <main class="chat-main">
      <!-- 会话标题栏 - 已屏蔽 -->
      <div class="chat-header" v-if="false && currentSessionId">
        <h2 class="session-name">{{ currentSessionTitle }}</h2>
        <div class="header-actions">
          <el-button type="text" @click="exportSession">
            <el-icon><Download /></el-icon> 导出
          </el-button>
          <el-button type="text" @click="deleteSession">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageList">
        <!-- 欢迎消息 -->
        <div
          v-if="messages.length === 0 && !currentSessionId && !loading"
          class="welcome-message"
        >
          <div class="welcome-avatar">
            <el-icon :size="48"><ChatDotRound /></el-icon>
          </div>
          <div class="welcome-content">
            <h3>您好！我是智能助手</h3>
            <p>
              我可以帮您分析数据、生成报告和回答问题。请输入您的问题，或选择下方的快速问题开始。
            </p>
          </div>
        </div>

        <!-- 消息内容 -->
        <div
          v-for="msg in messages"
          :key="msg.id"
          class="message-item"
          :class="msg.role"
        >
          <!-- 用户消息 - 右侧 -->
          <div v-if="msg.role === 'user'" class="message-wrapper user-message">
            <el-avatar class="message-avatar" :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="message-content">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-meta">
                {{ formatMessageTime(msg.timestamp) }}
              </div>
            </div>
          </div>

          <!-- 系统消息 - 左侧 -->
          <div v-else class="message-wrapper system-message">
            <el-avatar class="message-avatar" :size="40">
              <el-icon><ChatDotRound /></el-icon>
            </el-avatar>
            <div class="message-content">
              <!-- 根据 answer_type 渲染不同组件 -->
              <AnswerRenderer :answer="msg.answer" />

              <!-- 操作按钮 -->
              <div class="message-actions">
                <el-space
                  v-if="msg.suggestions && msg.suggestions.length > 0"
                  class="suggestion-buttons"
                  wrap
                >
                  <el-button
                    v-for="(s, index) in msg.suggestions"
                    :key="index"
                    size="small"
                    type="primary"
                    text
                    @click="askQuickQuestion(s)"
                  >
                    {{ s }}
                  </el-button>
                </el-space>

                <el-space class="meta-info" :size="8">
                  <span class="confidence" v-if="msg.confidence">
                    置信度: {{ (msg.confidence * 100).toFixed(0) }}%
                  </span>
                  <span class="response-time" v-if="msg.response_time_ms">
                    {{ msg.response_time_ms }}ms
                  </span>
                  <el-tag v-if="msg.used_ai" type="success" size="small">
                    机器人回答
                  </el-tag>
                </el-space>
              </div>
            </div>
          </div>
        </div>

        <!-- 正在思考提示 -->
        <div v-if="loading" class="message-item system">
          <div class="message-wrapper system-message">
            <el-avatar class="message-avatar" :size="40">
              <el-icon><ChatDotRound /></el-icon>
            </el-avatar>
            <div class="message-content">
              <div class="thinking-indicator">
                <span class="thinking-dot"></span>
                <span class="thinking-dot"></span>
                <span class="thinking-dot"></span>
                <span class="thinking-text">正在思考中...</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="input-area">
        <div style="display: flex; gap: 10px; align-items: center">
          <el-input
            v-model="question"
            placeholder="在这里输入问题，例如：技术部有多少泄露文件？"
            size="large"
            @keyup.enter="handleAsk"
            :disabled="loading"
            class="chat-input"
            type="textarea"
            style="flex: 1"
          >
          </el-input>
          <el-button
            type="primary"
            @click="handleAsk"
            :loading="loading"
            :disabled="loading"
          >
            发送
          </el-button>
        </div>
        <div class="input-hint">
          <span>按 Enter 发送消息，Shift + Enter 换行</span>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Check,
  Download,
  Delete,
  User,
  ChatDotRound,
} from "@element-plus/icons-vue";
import {
  askQuestion,
  // getSessionHistory, // 已屏蔽：接口不存在
  // getSessionList, // 已屏蔽：接口不存在
  // saveSession, // 已屏蔽：接口不存在
  // deleteSession as deleteSessionApi, // 已屏蔽：接口不存在
} from "../../servers";
import AnswerRenderer from "./components/AnswerRenderer.vue";

// 状态定义
const question = ref("");
const loading = ref(false);
const messages = ref([]);
const messageList = ref(null);
const currentSessionId = ref(null);
const currentSessionTitle = ref("");
const activeKey = ref(["today"]);

// 历史会话数据
const todaySessions = ref([]);
const yesterdaySessions = ref([]);
const thisWeekSessions = ref([]);

// 获取会话列表 - 已屏蔽：接口不存在
// const fetchSessionList = async () => {
//   try {
//     const res = await getSessionList();
//     if (res.code === 2000 && res.data) {
//       const sessions = res.data.sessions || res.data || [];
//       const today = new Date();
//       today.setHours(0, 0, 0, 0);
//       const yesterday = new Date(today);
//       yesterday.setDate(yesterday.getDate() - 1);
//       const thisWeek = new Date(today);
//       thisWeek.setDate(thisWeek.getDate() - 7);

//       todaySessions.value = sessions
//         .filter((s) => {
//           const date = new Date(s.created_at || s.timestamp || s.created_time);
//           return date >= today;
//         })
//         .map((s) => ({
//           id: s.session_id || s.id,
//           title: s.title || "未命名会话",
//           timestamp: new Date(
//             s.created_at || s.timestamp || s.created_time
//           ).getTime(),
//         }));

//       yesterdaySessions.value = sessions
//         .filter((s) => {
//           const date = new Date(s.created_at || s.timestamp || s.created_time);
//           return date >= yesterday && date < today;
//         })
//         .map((s) => ({
//           id: s.session_id || s.id,
//           title: s.title || "未命名会话",
//           timestamp: new Date(
//             s.created_at || s.timestamp || s.created_time
//           ).getTime(),
//         }));

//       thisWeekSessions.value = sessions
//         .filter((s) => {
//           const date = new Date(s.created_at || s.timestamp || s.created_time);
//           return date >= thisWeek && date < yesterday;
//         })
//         .map((s) => ({
//           id: s.session_id || s.id,
//           title: s.title || "未命名会话",
//           timestamp: new Date(
//             s.created_at || s.timestamp || s.created_time
//           ).getTime(),
//         }));
//     }
//   } catch (error) {
//     console.error("获取会话列表失败:", error);
//   }
// };

// 快速问题
const quickQuestions = ref([
  { id: 1, text: "技术部有多少泄露？" },
  { id: 2, text: "查看高危文件列表" },
  { id: 3, text: "最近的漏洞趋势" },
  { id: 4, text: "某个IP的关联分析" },
  { id: 5, text: "生成安全统计报告" },
]);

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
};

// 格式化消息时间
const formatMessageTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return date.toLocaleString();
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      const el = messageList.value;
      el.scrollTop = el.scrollHeight;
    }
  });
};

// 发送问题
const handleAsk = async () => {
  if (!question.value.trim()) {
    ElMessage.warning("请输入问题");
    return;
  }

  const currentQuestion = question.value;
  question.value = ""; // 清空输入框

  // 添加用户消息
  const userMsg = {
    id: Date.now(),
    role: "user",
    content: currentQuestion,
    timestamp: Date.now(),
  };
  messages.value.push(userMsg);

  // 如果是新会话，创建会话记录（仅本地，不保存到服务器）
  if (!currentSessionId.value) {
    const newSessionId = `s${Date.now()}`;
    currentSessionId.value = newSessionId;
    currentSessionTitle.value =
      currentQuestion.length > 20
        ? `${currentQuestion.substring(0, 20)}...`
        : currentQuestion;

    // 添加到今天的会话列表 - 已屏蔽：历史会话功能已禁用
    // todaySessions.value.unshift({
    //   id: newSessionId,
    //   title: currentSessionTitle.value,
    //   timestamp: Date.now(),
    // });
  }

  loading.value = true;
  scrollToBottom();

  try {
    // 调用API
    const res = await askQuestion({
      question: currentQuestion,
      session_id: currentSessionId.value,
    });

    if (res.code === 2000) {
      // 添加系统回答
      const systemMsg = {
        id: Date.now() + 1,
        role: "system",
        answer: res.data.answer,
        matched_rule_id: res.data.matched_rule_id,
        used_ai: res.data.used_ai,
        confidence: res.data.confidence,
        response_time_ms: res.data.response_time_ms,
        suggestions: res.data.suggestions,
        timestamp: Date.now(),
      };
      messages.value.push(systemMsg);

      // 滚动到底部
      scrollToBottom();

      // 保存会话到服务器 - 已屏蔽：接口不存在
      // try {
      //   await saveSession({
      //     session_id: currentSessionId.value,
      //     messages: messages.value,
      //     title: currentSessionTitle.value,
      //   });
      // } catch (saveError) {
      //   console.error("保存会话失败:", saveError);
      // }
    } else {
      ElMessage.error(res.message || "请求失败");
    }
  } catch (error) {
    ElMessage.error("请求异常，请稍后重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 快速提问
const askQuickQuestion = (text) => {
  question.value = text;
  handleAsk();
};

// 新建会话
const newSession = () => {
  // 确认是否保存当前会话
  if (currentSessionId.value && messages.value.length > 0) {
    ElMessageBox.confirm("当前会话内容将被保存，是否继续？", "确认新建会话", {
      confirmButtonText: "继续",
      cancelButtonText: "取消",
      type: "info",
    })
      .then(() => {
        resetSession();
      })
      .catch(() => {});
  } else {
    resetSession();
  }
};

// 重置会话
const resetSession = () => {
  messages.value = [];
  currentSessionId.value = null;
  currentSessionTitle.value = "";
  question.value = "";
};

// 加载历史会话 - 已屏蔽：接口不存在
// const loadSession = async (session) => {
//   currentSessionId.value = session.id;
//   currentSessionTitle.value = session.title;
//   loading.value = true;

//   try {
//     // 从API获取会话历史
//     const res = await getSessionHistory(session.id);
//     if (res.code === 2000) {
//       messages.value = (res.data.messages || []).map((msg) => ({
//         ...msg,
//         id: msg.id || Date.now() + Math.random(),
//         timestamp: msg.timestamp || Date.now(),
//       }));
//       scrollToBottom();
//     } else {
//       ElMessage.error(res.message || "加载会话失败");
//     }
//   } catch (error) {
//     ElMessage.error("加载会话异常");
//     console.error(error);
//   } finally {
//     loading.value = false;
//   }
// };

// 导出会话
const exportSession = () => {
  if (!currentSessionId.value) {
    ElMessage.warning("没有当前会话可导出");
    return;
  }

  // 简单的导出功能，实际应用中应调用API导出
  const content = messages.value
    .map((msg) => {
      const role = msg.role === "user" ? "用户" : "系统";
      return `[${formatMessageTime(msg.timestamp)}] ${role}: ${
        msg.content || JSON.stringify(msg.answer)
      }`;
    })
    .join("\n\n");

  const blob = new Blob([content], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `会话_${currentSessionTitle.value.replace(/\s+/g, "_")}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  ElMessage.success("会话导出成功");
};

// 删除会话 - 已屏蔽：接口不存在
// const deleteSession = () => {
//   if (!currentSessionId.value) {
//     ElMessage.warning("没有当前会话可删除");
//     return;
//   }

//   ElMessageBox.confirm("此操作将永久删除当前会话，是否继续？", "确认删除会话", {
//     confirmButtonText: "确认",
//     cancelButtonText: "取消",
//     type: "warning",
//   })
//     .then(async () => {
//       try {
//         // 调用API删除会话
//         const res = await deleteSessionApi(currentSessionId.value);
//         if (res.code === 2000) {
//           ElMessage.success("会话删除成功");

//           // 从本地会话列表中移除
//           todaySessions.value = todaySessions.value.filter(
//             (s) => s.id !== currentSessionId.value
//           );
//           yesterdaySessions.value = yesterdaySessions.value.filter(
//             (s) => s.id !== currentSessionId.value
//           );
//           thisWeekSessions.value = thisWeekSessions.value.filter(
//             (s) => s.id !== currentSessionId.value
//           );

//           // 重置会话
//           resetSession();
//         } else {
//           ElMessage.error(res.message || "删除会话失败");
//         }
//       } catch (error) {
//         ElMessage.error("删除会话异常");
//         console.error(error);
//       }
//     })
//     .catch(() => {});
// };

// 监听消息列表变化，自动滚动到底部
const observer = new MutationObserver(scrollToBottom);
onMounted(() => {
  if (messageList.value) {
    observer.observe(messageList.value, { childList: true, subtree: true });
  }
  // 初始化时获取会话列表 - 已屏蔽：接口不存在
  // fetchSessionList();
});
</script>

<style scoped lang="scss">
.qa-chat-container {
  display: flex;
  height: calc(100vh - 184px);
  background: #f5f5f5;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 左侧边栏 */
.sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e8e8e8;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.new-session-btn {
  width: 100%;
  margin-bottom: 16px;
}

.session-collapse {
  margin-bottom: 24px;
  flex: 1;
  overflow-y: auto;
}

:deep(.el-collapse-item__header) {
  font-weight: 500;
  padding: 8px 0;
}

:deep(.el-collapse-item__content) {
  padding: 8px 0;
}

.session-item {
  padding: 10px 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  min-height: 40px;
}

.session-item:hover {
  background: #f0f2f5;
}

.session-item.active {
  background: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

.session-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  font-size: 14px;
}

.session-time {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
  flex-shrink: 0;
}

.quick-questions {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.quick-question-list {
  width: 100%;
}

.quick-question-btn {
  width: 100%;
  text-align: left;
  justify-content: flex-start;
  margin-bottom: 8px;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    transform: translateX(4px);
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
  }
}

/* 主内容区 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  position: relative;
  overflow: hidden;
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
  flex-shrink: 0;
}

.session-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 24px 20px;
  background: linear-gradient(to bottom, #f5f7fa 0%, #ffffff 100%);
  min-height: 0;
  position: relative;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  padding: 60px 40px;
}

.welcome-avatar {
  color: #667eea;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.welcome-content h3 {
  font-size: 28px;
  margin-bottom: 16px;
  color: #333;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.welcome-content p {
  font-size: 16px;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.8;
}

.message-item {
  margin-bottom: 24px;
  display: flex;
  width: 100%;
}

.message-item.user {
  justify-content: flex-end;
}

.message-item.system {
  justify-content: flex-start;
}

.message-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  max-width: 75%;
  min-width: 200px;
}

.user-message {
  flex-direction: row-reverse;
}

.system-message {
  flex-direction: row;
}

.message-avatar {
  flex-shrink: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.user-message .message-avatar {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 2px 8px rgba(245, 87, 108, 0.3);
}

.message-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.message-text {
  padding: 14px 18px;
  border-radius: 12px;
  background: #fff;
  word-break: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  line-height: 1.6;
  font-size: 14px;
  color: #333;
  border: 1px solid #f0f0f0;
}

.user-message .message-text {
  // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #000;
  border: none;
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.25);
}

/* AI回答内容样式 */
.system-message .message-content > :deep(.answer-renderer) {
  padding: 14px 18px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.message-meta {
  font-size: 11px;
  color: #999;
  margin-top: 6px;
  padding: 0 4px;
}

.user-message .message-meta {
  text-align: right;
}

.system-message .message-meta {
  text-align: left;
}

/* 正在思考指示器 */
.thinking-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 18px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.thinking-text {
  font-size: 14px;
  color: #999;
  font-style: italic;
}

.thinking-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #409eff;
  animation: thinking-bounce 1.4s infinite ease-in-out;
}

.thinking-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes thinking-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

.message-actions {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.suggestion-buttons {
  flex: 1;
}

.meta-info {
  font-size: 11px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.confidence,
.response-time {
  color: #999;
  font-size: 11px;
}

/* 输入区域 */
.input-area {
  padding: 20px 24px;
  border-top: 1px solid #e8e8e8;
  background: #fff;
  flex-shrink: 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
}

.chat-input {
  width: 100%;
}

:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group__append .el-button) {
  padding: 0 20px;
}

.input-hint {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .sidebar {
    width: 240px;
  }

  .message-content {
    max-width: calc(100% - 48px);
  }
}

@media (max-width: 576px) {
  .qa-chat-container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e8e8e8;
  }

  .chat-main {
    flex: 1;
    min-height: 0;
  }
}
</style>
